<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>大视频分析 - 视频理解分析工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .nav-bar {
            background: #f8f9fa;
            padding: 15px 30px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .nav-link {
            color: #495057;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            background: #e9ecef;
            color: #007bff;
        }

        .nav-link.active {
            background: #007bff;
            color: white;
        }

        .content {
            padding: 30px;
        }

        .form-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
        }

        .form-section h3 {
            margin-bottom: 20px;
            color: #495057;
            font-size: 1.2rem;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #495057;
        }

        .form-control {
            width: 100%;
            padding: 12px;
            border: 1px solid #ced4da;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .result-section {
            display: none;
            background: white;
            border-radius: 12px;
            padding: 25px;
            border: 1px solid #e9ecef;
            margin-top: 30px;
        }

        .result-section.show {
            display: block;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9ecef;
        }

        .result-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }

        .stat-number {
            font-size: 1.5rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #6c757d;
            font-size: 12px;
        }

        .timeline {
            margin-bottom: 30px;
        }

        .timeline-item {
            background: #f8f9fa;
            border-left: 4px solid #667eea;
            padding: 15px 20px;
            margin-bottom: 15px;
            border-radius: 0 8px 8px 0;
        }

        .timeline-time {
            font-weight: 600;
            color: #667eea;
            margin-bottom: 8px;
        }

        .timeline-content {
            color: #495057;
            line-height: 1.5;
        }

        .summary-section {
            background: #e7f3ff;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }

        .summary-section h4 {
            color: #007bff;
            margin-bottom: 15px;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 15px;
            }

            .content {
                padding: 20px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .nav-bar {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎬 大视频分析</h1>
            <p>智能拆分长视频，分段分析后汇总结果</p>
        </div>

        <div class="nav-bar">
            <a href="/" class="nav-link">🏠 视频分析</a>
            <a href="/test" class="nav-link">🧪 测试上传</a>
            <a href="/videos" class="nav-link">📹 视频管理</a>
            <a href="/large-analysis" class="nav-link active">🎞️ 大视频分析</a>
        </div>

        <div class="content">
            <div id="alert-container"></div>

            <div class="form-section">
                <h3>📁 上传大视频文件</h3>
                <form id="analysisForm">
                    <div class="form-group">
                        <label for="videoFile">选择视频文件</label>
                        <input type="file" id="videoFile" class="form-control" accept="video/*" required>
                    </div>

                    <div class="form-group">
                        <label for="prompt">分析提示词</label>
                        <textarea id="prompt" class="form-control" rows="4" required
                                  placeholder="请详细描述视频内容，包括时间线、关键事件、人物动作等...">详述视频中的操作步骤，带上时间</textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="splitMethod">拆分方法</label>
                            <select id="splitMethod" class="form-control">
                                <option value="auto">自动选择</option>
                                <option value="duration">按时长拆分</option>
                                <option value="scene">按场景拆分</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="segmentDuration">片段时长（秒）</label>
                            <input type="number" id="segmentDuration" class="form-control" value="60" min="30" max="300">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="maxSegments">最大片段数</label>
                            <input type="number" id="maxSegments" class="form-control" value="50" min="5" max="50">
                        </div>

                        <div class="form-group">
                            <label for="minSegmentDuration">最小片段时长（秒）</label>
                            <input type="number" id="minSegmentDuration" class="form-control" value="10" min="5" max="30">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="analysisMode">分析模式</label>
                        <select id="analysisMode" class="form-control">
                            <option value="sequential">顺序分析（稳定）</option>
                            <option value="parallel">并行分析（快速）</option>
                            <option value="hybrid">混合模式（推荐）</option>
                        </select>
                    </div>

                    <!-- 分段/汇总提示词（在系统判断需要拆分后显示） -->
                    <div id="promptTemplatesSection" style="display:none;">
                        <div class="form-group">
                            <label for="segmentPromptTemplate">分段提示词模板</label>
                            <textarea id="segmentPromptTemplate" class="form-control" rows="6" placeholder="系统会自动生成，包含 {segment_id}、{total_segments}、{start_time}、{end_time} 占位符"></textarea>
                            <small style="color:#6c757d;">
                            提示：支持以下占位符——
                            {base_prompt} 原始提示词全文；
                            {segment_id}/{segment_no} 当前片段序号(从1开始)；
                            {segment_index} 当前片段索引(从0开始)；
                            {total_segments} 总片段数量；
                            {start_time}/{end_time} 带 s 的起止时间；
                            {start_sec}/{end_sec} 纯数字起止时间(秒)；
                            {duration} 片段时长(带 s)；
                            {segment_filename} 片段文件名；
                            {segment_url} 片段访问 URL。
                        </small>
                        </div>
                        <div class="form-group">
                            <label for="aggregatePrompt">汇总提示词</label>
                            <textarea id="aggregatePrompt" class="form-control" rows="6" placeholder="系统会自动生成，用于合并各分片 JSON 为最终答案"></textarea>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary" id="analyzeBtn">
                        🚀 开始大视频分析
                    </button>
                </form>
            </div>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p id="loadingText">正在分析大视频，请耐心等待...</p>
                <p style="font-size: 14px; color: #6c757d; margin-top: 10px;">
                    大视频分析需要较长时间，系统会自动拆分视频并逐段分析
                </p>
            </div>

            <div class="result-section" id="streamSection" style="display:none;">
                <div class="result-header">
                    <h3>🧠 实时思考流</h3>
                </div>
                <div id="streamContent" style="display:flex; flex-direction:column; gap:10px;"></div>
            </div>

            <div class="result-section" id="resultSection">
                <div class="result-header">
                    <h3>📊 分析结果</h3>
                    <div style="display:flex; gap:10px;">
                        <button class="btn btn-secondary" onclick="downloadResult()">📥 下载结果</button>
                        <button class="btn btn-secondary" onclick="exportPDF()">📄 导出PDF</button>
                    </div>
                </div>

                <div class="result-stats" id="resultStats">
                    <!-- 统计信息将在这里显示 -->
                </div>

                <div class="summary-section" id="summarySection">
                    <h4>🎯 整体摘要</h4>
                    <div id="overallSummary"></div>
                </div>

                <div class="insights-section" id="insightsSection" style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0;">
                    <h4>💡 关键洞察</h4>
                    <div id="keyInsights">
                        <!-- 关键洞察内容将在这里显示 -->
                    </div>
                </div>

                <div class="timeline" id="timeline">
                    <h4>⏱️ 时间线分析</h4>
                    <div id="timelineContent">
                        <!-- 时间线内容将在这里显示 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentResult = null;

        document.getElementById('analysisForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            await analyzeVideo();
        });

        let promptsReady = false;

        async function analyzeVideo() {
            const fileInput = document.getElementById('videoFile');
            const promptInput = document.getElementById('prompt');
            const splitMethodInput = document.getElementById('splitMethod');
            const segmentDurationInput = document.getElementById('segmentDuration');
            const maxSegmentsInput = document.getElementById('maxSegments');
            const minSegmentDurationInput = document.getElementById('minSegmentDuration');
            const analysisModeInput = document.getElementById('analysisMode');
            const analyzeBtn = document.getElementById('analyzeBtn');
            const promptTemplatesSection = document.getElementById('promptTemplatesSection');
            const segmentPromptTemplateInput = document.getElementById('segmentPromptTemplate');
            const aggregatePromptInput = document.getElementById('aggregatePrompt');

            if (!fileInput.files[0]) {
                showAlert('请选择视频文件', 'error');
                return;
            }

            if (!promptInput.value.trim()) {
                showAlert('请输入分析提示词', 'error');
                return;
            }

            // 如果已经生成并确认过提示词，直接执行分析（改为SSE实时思考流）
            if (promptsReady) {
                showLoading('正在开始分段分析...');
                analyzeBtn.disabled = true;
                hideResult();
                document.getElementById('streamSection').style.display = 'block';
                const streamBox = document.getElementById('streamContent');
                streamBox.innerHTML = '';

                try {
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    formData.append('prompt', promptInput.value);
                    formData.append('split_method', splitMethodInput.value);
                    formData.append('segment_duration', segmentDurationInput.value);
                    formData.append('max_segments', maxSegmentsInput.value);
                    formData.append('min_segment_duration', minSegmentDurationInput.value);
                    formData.append('analysis_mode', analysisModeInput.value);
                    formData.append('segment_prompt_template', segmentPromptTemplateInput.value || '');
                    formData.append('aggregate_prompt', aggregatePromptInput.value || '');

                    const resp = await fetch('/api/analyze-large-stream', {
                        method: 'POST',
                        body: formData
                    });

                    if (!resp.ok || !resp.body) {
                        throw new Error('SSE连接失败');
                    }

                    const reader = resp.body.getReader();
                    const decoder = new TextDecoder('utf-8');
                    let buffer = '';

                    // 保存各片段的卡片元素 {index: {card, header, body, status, time}}
                    const streamItems = new Map();

                    function ensureSegmentCard(index, opts = {}) {
                        if (streamItems.has(index)) return streamItems.get(index);
                        const card = document.createElement('div');
                        card.style.border = '1px solid #eee';
                        card.style.borderRadius = '6px';
                        card.style.background = '#fff';
                        card.style.overflow = 'hidden';
                        card.style.userSelect = 'none';
                        card.dataset.index = index;

                        const header = document.createElement('div');
                        header.style.padding = '10px';
                        header.style.cursor = 'pointer';
                        header.style.fontSize = '12px';
                        header.style.color = '#6c757d';
                        header.style.display = 'flex';
                        header.style.alignItems = 'center';
                        header.style.justifyContent = 'space-between';

                        const title = document.createElement('div');
                        title.textContent = `片段 #${(index ?? 0) + 1} · ${opts.status || 'running'}`;

                        const time = document.createElement('div');
                        time.textContent = opts.time || '';

                        header.appendChild(title);
                        header.appendChild(time);

                        const body = document.createElement('div');
                        body.style.padding = '10px';
                        body.style.borderTop = '1px solid #f0f0f0';
                        body.style.display = 'none';
                        body.style.whiteSpace = 'pre-wrap';
                        body.textContent = '';

                        header.addEventListener('click', () => {
                            const open = body.style.display !== 'none';
                            body.style.display = open ? 'none' : 'block';
                        });

                        card.appendChild(header);
                        card.appendChild(body);
                        streamBox.appendChild(card);
                        streamBox.scrollTop = streamBox.scrollHeight;
                        const entry = { card, header, body, title, time };
                        streamItems.set(index, entry);
                        return entry;
                    }

                    function updateSegmentHeader(index, status, timeStr) {
                        const entry = ensureSegmentCard(index);
                        entry.title.textContent = `片段 #${(index ?? 0) + 1} · ${status}`;
                        if (timeStr) entry.time.textContent = timeStr;
                    }

                    function appendThinking(item) {
                        const entry = ensureSegmentCard(item.segment_index, { status: item.status, time: item.analyzed_at });
                        const hasContent = !!(item.analysis_result && item.analysis_result.trim());
                        if (hasContent) {
                            // 仅在有内容时展示正文
                            entry.body.style.display = 'block';
                            entry.body.innerHTML = escapeHtml(item.analysis_result);
                            streamBox.scrollTop = streamBox.scrollHeight;
                        } else {
                            // 无内容则不显示正文（避免“该片段无输出”占位）
                            entry.body.style.display = 'none';
                            entry.body.innerHTML = '';
                        }
                        updateSegmentHeader(item.segment_index, item.status || 'success', item.analyzed_at || '');
                    }

                    while (true) {
                        const { value, done } = await reader.read();
                        if (done) break;
                        buffer += decoder.decode(value, { stream: true });

                        const events = buffer.split('\n\n');
                        buffer = events.pop();
                        for (const raw of events) {
                            const lines = raw.split('\n');
                            let event = 'message';
                            let data = '';
                            for (const line of lines) {
                                if (line.startsWith('event:')) event = line.slice(6).trim();
                                else if (line.startsWith('data:')) data += line.slice(5).trim();
                            }
                            if (!data) continue;
                            const parsed = JSON.parse(data);
                            if (event === 'segment_start') {
                                // 预先生成条目，默认收起
                                const entry = ensureSegmentCard(parsed.segment_index, { status: parsed.status || 'running', time: parsed.started_at });
                                entry.body.style.display = 'none';
                                entry.body.textContent = '思考中…';
                            } else if (event === 'segment_delta') {
                                const entry = ensureSegmentCard(parsed.segment_index);
                                // 追加增量文本，但不强制展开，让用户自控
                                entry.body.innerHTML += escapeHtml(parsed.delta || '');
                            } else if (event === 'segment_progress') {
                                appendThinking(parsed);
                            } else if (event === 'final_result') {
                                currentResult = parsed;
                                displayResult(parsed);
                                showAlert('大视频分析完成！', 'success');
                            } else if (event === 'error') {
                                showAlert('流式错误: ' + (parsed.message || ''), 'error');
                            }
                        }
                    }
                } catch (error) {
                    console.error('Analysis stream error:', error);
                    showAlert('网络错误，分析失败', 'error');
                } finally {
                    hideLoading();
                    analyzeBtn.disabled = false;
                    promptsReady = false;
                }
                return;
            }

            // 第一步：先进行拆分预判
            showLoading('正在拆分视频以评估是否需要分段...');
            analyzeBtn.disabled = true;
            hideResult();

            try {
                const splitForm = new FormData();
                splitForm.append('file', fileInput.files[0]);
                splitForm.append('method', splitMethodInput.value === 'auto' ? 'duration' : splitMethodInput.value);
                splitForm.append('segment_duration', segmentDurationInput.value);
                splitForm.append('max_segments', maxSegmentsInput.value);

                const splitResp = await fetch('/api/split-video', { method: 'POST', body: splitForm });
                const splitJson = await splitResp.json();
                if (!splitJson.success) {
                    showAlert('拆分失败: ' + (splitJson.message || '未知错误'), 'error');
                    return;
                }

                const needSplit = (splitJson.data && splitJson.data.need_split) || (splitJson.data && splitJson.data.segment_count > 1);

                if (needSplit) {
                    // 第二步：调用提示词生成接口
                    updateLoadingText('需要分段，正在生成分段/汇总提示词...');
                    const genForm = new FormData();
                    genForm.append('original_prompt', promptInput.value);
                    const genResp = await fetch('/api/generate-prompts', { method: 'POST', body: genForm });
                    const genJson = await genResp.json();
                    if (genJson.success) {
                        // 展示并填充两个输入框，等待用户确认
                        promptTemplatesSection.style.display = 'block';
                        segmentPromptTemplateInput.value = genJson.segment_prompt_template || '';
                        aggregatePromptInput.value = genJson.aggregate_prompt || '';
                        showAlert('已生成分段/汇总提示词，请检查并点击“开始大视频分析”继续', 'info');
                        promptsReady = true;
                        analyzeBtn.textContent = '✅ 继续分析';
                        analyzeBtn.disabled = false;
                        hideLoading();
                        return; // 等用户确认后再次提交
                    } else {
                        showAlert('提示词生成失败，您可以手动填写后继续', 'error');
                        promptTemplatesSection.style.display = 'block';
                        promptsReady = true;
                        analyzeBtn.textContent = '✅ 继续分析';
                        analyzeBtn.disabled = false;
                        hideLoading();
                        return;
                    }
                } else {
                    // 不需要分段，直接分析
                    updateLoadingText('无需分段，直接分析...');
                    const formData = new FormData();
                    formData.append('file', fileInput.files[0]);
                    formData.append('prompt', promptInput.value);
                    formData.append('split_method', splitMethodInput.value);
                    formData.append('segment_duration', segmentDurationInput.value);
                    formData.append('max_segments', maxSegmentsInput.value);
                    formData.append('min_segment_duration', minSegmentDurationInput.value);
                    formData.append('analysis_mode', analysisModeInput.value);

                    const response = await fetch('/api/analyze-large', { method: 'POST', body: formData });
                    const result = await response.json();
                    if (result.success) {
                        currentResult = result.result;
                        showAlert('分析完成！', 'success');
                        displayResult(result.result);
                    } else {
                        showAlert('分析失败: ' + (result.message || '未知错误'), 'error');
                    }
                }
            } catch (error) {
                console.error('Analysis error:', error);
                showAlert('网络错误，分析失败', 'error');
            } finally {
                if (!promptsReady) {
                    hideLoading();
                    analyzeBtn.disabled = false;
                }
            }
        }

        function displayResult(result) {
            // 显示统计信息
            const statsHtml = `
                <div class="stat-card">
                    <div class="stat-number">${result.segment_count || 0}</div>
                    <div class="stat-label">总片段数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${result.successful_segments || 0}</div>
                    <div class="stat-label">成功分析</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${Math.round(result.total_duration || 0)}s</div>
                    <div class="stat-label">总时长</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${result.split_method || 'unknown'}</div>
                    <div class="stat-label">拆分方法</div>
                </div>
            `;
            document.getElementById('resultStats').innerHTML = statsHtml;

            // 显示整体摘要
            document.getElementById('overallSummary').innerHTML = 
                result.overall_summary || '暂无整体摘要';

            // 显示关键洞察
            if (result.key_insights) {
                const insights = result.key_insights;
                const insightsHtml = `
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                        ${insights.key_actions && insights.key_actions.length > 0 ? `
                        <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #28a745;">
                            <h5 style="color: #28a745; margin-bottom: 10px;">🎬 关键动作</h5>
                            <ul style="margin: 0; padding-left: 20px;">
                                ${insights.key_actions.map(action => `<li>${action}</li>`).join('')}
                            </ul>
                        </div>
                        ` : ''}
                        
                        ${insights.important_timestamps && insights.important_timestamps.length > 0 ? `
                        <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #007bff;">
                            <h5 style="color: #007bff; margin-bottom: 10px;">⏰ 重要时间点</h5>
                            <ul style="margin: 0; padding-left: 20px;">
                                ${insights.important_timestamps.map(time => `<li>${time}</li>`).join('')}
                            </ul>
                        </div>
                        ` : ''}
                        
                        ${insights.technical_details && insights.technical_details.length > 0 ? `
                        <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #ffc107;">
                            <h5 style="color: #ffc107; margin-bottom: 10px;">🔧 技术细节</h5>
                            <ul style="margin: 0; padding-left: 20px;">
                                ${insights.technical_details.map(detail => `<li>${detail}</li>`).join('')}
                            </ul>
                        </div>
                        ` : ''}
                        
                        ${insights.main_themes && insights.main_themes.length > 0 ? `
                        <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #6f42c1;">
                            <h5 style="color: #6f42c1; margin-bottom: 10px;">🎯 主要主题</h5>
                            <ul style="margin: 0; padding-left: 20px;">
                                ${insights.main_themes.map(theme => `<li>${theme}</li>`).join('')}
                            </ul>
                        </div>
                        ` : ''}
                        
                        ${insights.recommendations && insights.recommendations.length > 0 ? `
                        <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #dc3545;">
                            <h5 style="color: #dc3545; margin-bottom: 10px;">💡 建议</h5>
                            <ul style="margin: 0; padding-left: 20px;">
                                ${insights.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                            </ul>
                        </div>
                        ` : ''}
                    </div>
                `;
                document.getElementById('keyInsights').innerHTML = insightsHtml;
            } else {
                document.getElementById('keyInsights').innerHTML = 
                    '<p style="color: #6c757d;">暂无关键洞察数据</p>';
            }

            // 显示时间线
            if (result.timeline_summary && result.timeline_summary.length > 0) {
                const timelineHtml = result.timeline_summary.map(item => `
                    <div class="timeline-item">
                        <div class="timeline-time">${item.time_range} (${item.duration})</div>
                        <div class="timeline-content">${item.summary}</div>
                    </div>
                `).join('');
                document.getElementById('timelineContent').innerHTML = timelineHtml;
            } else {
                document.getElementById('timelineContent').innerHTML = 
                    '<p style="color: #6c757d;">暂无时间线数据</p>';
            }

            showResult();
        }

        function showLoading(text) {
            document.getElementById('loadingText').textContent = text || '正在处理...';
            document.getElementById('loading').classList.add('show');
        }

        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        function updateLoadingText(text) {
            document.getElementById('loadingText').textContent = text;
        }

        function showResult() {
            document.getElementById('resultSection').classList.add('show');
        }

        function hideResult() {
            document.getElementById('resultSection').classList.remove('show');
        }

        function showAlert(message, type) {
            const container = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 
                              type === 'info' ? 'alert-info' : 'alert-error';
            
            container.innerHTML = `
                <div class="alert ${alertClass}">
                    ${escapeHtml(message)}
                </div>
            `;

            setTimeout(() => {
                container.innerHTML = '';
            }, 5000);
        }

        function downloadResult() {
            if (!currentResult) {
                showAlert('没有可下载的结果', 'error');
                return;
            }

            const dataStr = JSON.stringify(currentResult, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            
            const link = document.createElement('a');
            link.href = url;
            link.download = `large_video_analysis_${new Date().getTime()}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        async function exportPDF() {
            try {
                // 使用浏览器的打印到PDF能力，保留可选中文字（矢量文本）
                const printable = buildPrintableHTML();
                const w = window.open('', '_blank');
                if (!w) {
                    showAlert('弹窗被拦截，请允许此站点的弹窗以导出PDF', 'error');
                    return;
                }
                w.document.open();
                w.document.write(printable);
                w.document.close();
                // 等待样式与图片加载后再打印
                w.onload = () => {
                    w.focus();
                    w.print(); // 用户在打印对话框中选择“另存为PDF”
                };
            } catch (e) {
                console.error('exportPDF error:', e);
                showAlert('导出 PDF 失败，请重试', 'error');
            }
        }

        function buildPrintableHTML() {
            // 采集当前页面数据（含三段提示词，保留换行）
            const prompt = document.getElementById('prompt')?.value || '';
            const segmentPromptTemplate = document.getElementById('segmentPromptTemplate')?.value || '';
            const aggregatePrompt = document.getElementById('aggregatePrompt')?.value || '';
            const stats = document.getElementById('resultStats')?.innerHTML || '';
            const overall = document.getElementById('overallSummary')?.innerHTML || '';
            const insights = document.getElementById('keyInsights')?.innerHTML || '';
            const timeline = document.getElementById('timelineContent')?.innerHTML || '';

            const style = `
                <style>
                    * { box-sizing: border-box; }
                    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
                    h1,h2,h3,h4,h5 { margin: 0 0 8px; }
                    .section { margin-bottom: 16px; }
                    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; }
                    .card { border: 1px solid #e9ecef; border-radius: 8px; padding: 12px; }
                    .muted { color: #6c757d; font-size: 12px; }
                    pre { white-space: pre-wrap; word-break: break-word; border: 1px dashed #e9ecef; border-radius: 8px; padding: 10px; background: #fafafa; }
                    ul { margin: 6px 0 0 18px; }
                    .timeline-item { border-left: 4px solid #667eea; padding: 8px 12px; margin: 8px 0; background: #f8f9fa; border-radius: 0 8px 8px 0; }

                    @media print {
                        @page { size: A4; margin: 12mm; }
                        .no-print { display: none !important; }
                    }
                </style>
            `;

            const html = `
                <!doctype html>
                <html>
                <head>
                    <meta charset="utf-8">${style}
                    <title>large_video_analysis_${new Date().getTime()}</title>
                </head>
                <body>
                    <div class="section">
                        <h2>📄 大视频分析导出</h2>
                        <div class="muted">导出时间：${new Date().toLocaleString()}</div>
                    </div>

                    <div class="section">
                        <h3>🧩 基础提示词</h3>
                        <pre>${escapeHtml(prompt)}</pre>
                    </div>

                    <div class="section">
                        <h3>🧩 分段提示词模板</h3>
                        <pre>${escapeHtml(segmentPromptTemplate)}</pre>
                    </div>

                    <div class="section">
                        <h3>🧩 汇总提示词</h3>
                        <pre>${escapeHtml(aggregatePrompt)}</pre>
                    </div>

                    <div class="section">
                        <h3>📊 统计信息</h3>
                        <div class="grid">${stats}</div>
                    </div>

                    <div class="section">
                        <h3>🧠 整体摘要</h3>
                        <div class="card">${overall || '<span class="muted">暂无</span>'}</div>
                    </div>

                    <div class="section">
                        <h3>💡 关键洞察</h3>
                        ${insights || '<div class="muted">暂无</div>'}
                    </div>

                    <div class="section">
                        <h3>⏱️ 时间线</h3>
                        ${timeline || '<div class="muted">暂无</div>'}
                    </div>
                </body>
                </html>
            `;
            return html;
        }

        function loadScript(src) {
            return new Promise((resolve, reject) => {
                const s = document.createElement('script');
                s.src = src;
                s.onload = resolve;
                s.onerror = reject;
                document.body.appendChild(s);
            });
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 文件选择时显示文件信息
        document.getElementById('videoFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const sizeMB = (file.size / 1024 / 1024).toFixed(2);
                showAlert(`已选择文件: ${file.name} (${sizeMB} MB)`, 'info');
            }
        });
    </script>
</body>
</html>